package com.demo2do.mobile.web.controller.trading;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.mobile.handler.PaymentHandler;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("")
public class PaymentController {
    
    private static Logger logger = LoggerFactory.getLogger(PaymentController.class);
    
    @Autowired
    private PaymentHandler paymentHandler;
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/shop", method = RequestMethod.GET)
    public ModelAndView shop() {
    	ModelAndView modelAndView = new ModelAndView("trading/wechat-payment");
    	return modelAndView;
    }
    
    /**
     * 
     * @param openid
     * @param orderId
     * @param currentUrl
     * @param request
     * @return
     */
    @RequestMapping(value = "/wxpay/prepare", method = RequestMethod.POST)
    public @ResponseBody String wechatpayPrepare(@CookieValue(name = "demo2do-mobile-openid") String openid,
    											 @RequestParam("orderId") Long orderId,
                                                 @RequestParam("currentUrl") String currentUrl,
                                                 HttpServletRequest request) {
        
        
        
        Result result = new Result();
        
        try {
        	
        	// Get user's openid
        	//Cookie openidCookie = WebUtils.getCookie(request, Constant.OPENID_KEY);
        	if(StringUtils.isBlank(openid)) {
        		result.fail("500").message("请先微信授权");
        		return JsonUtils.toJson(result);
        	}
        	
            logger.trace("PaymentController#wechatpayPrepare() - Get openid [{}] from cookie.", openid);
            
            // Get remote IP address, check NGINX real IP header first
            String xRealIpHeader = request.getHeader("X-Real-IP");  // Only available after NGINX redirect
            String remoteIp = StringUtils.isBlank(xRealIpHeader) ? request.getRemoteAddr() : xRealIpHeader;
            logger.trace("#wechatpayPrepare() - Get remote IP address [{}].", remoteIp);
            
            // TODO save request record into database
            
            // Construct necessary request data
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("order_no", orderId.toString());
            parameters.put("request_no", String.valueOf(System.currentTimeMillis()));
            parameters.put("user_id", openid);
            parameters.put("channel", "wechatpay");
            parameters.put("amount", "1");
            parameters.put("subject", "测试产品123");
            
            Map<String, Object> wechatPayContext  = paymentHandler.generateWechatPayContext(parameters);
            logger.trace("#wechatpayPrepare() - Get wechatPayContext here [{}]", JsonUtils.toJson(wechatPayContext));

            Map<String, Object> jsConfig = paymentHandler.requestJsConfig(currentUrl);
            
            result.success()
            	  .data("payConfig", wechatPayContext)
            	  .data("jsConfig", jsConfig);
            
        } catch (BusinessException e) {
        	result.fail("500").message(e.getMessage());
        } catch (Exception e) {
        	
        	logger.error("#wechatpayPrepare - occurs error", e);
        	
        	result.fail("500").message("请求支付数据失败");
		}
        
        return JsonUtils.toJson(result);
    }
    
    /**
     * 
     * @param requestNo
     * @return
     */
    @RequestMapping("/orders/{requestNo}/complete")
    public ModelAndView complete(@PathVariable("requestNo") Long requestNo) {
    	ModelAndView modelAndView = new ModelAndView("trading/order-complete");
    	
    	modelAndView.addObject("requestNo", requestNo);
    	
    	return modelAndView;
    }
    
}
